/*
 * Copyright (C) 2010 TopCoder Inc., All Rights Reserved.
 */
package com.hercules.android.receiver.commands;

import org.json.JSONException;
import org.json.JSONObject;

import com.hercules.android.receiver.Receiver;
import com.hercules.android.receiver.ReceiverUtil;
import com.hercules.android.receiver.XREObjectFormatterException;
import com.hercules.android.receiver.entities.XREObject;

/**
 * <p>
 * This command handler class will handle the SET command.
 * </p>
 * 
 * @author TCSASSEMBER
 * @version 1.0
 */
public class XRESetCommandHandler extends XRECommandHandler {
    /**
     * Create a new <code>XRESetCommandHandler</code> with the
     * <code>Receiver</code> instance.
     * 
     * @param receiver
     *            the <code>Receiver</code> instance.
     * @throws IllegalArgumentException
     *             if argument is null
     */
    public XRESetCommandHandler(Receiver receiver) {
        super(receiver);
    }

    /**
     * Process the SET command message.
     * 
     * @param message
     *            the command message to be processed.
     * @throws XRECommandHandlerException
     *             if any other error occurs
     */
    public void processCommand(JSONObject message) throws XRECommandHandlerException {
        int targetId = 0;
        String targetPath = null;

        try {
            if (message.has("targetId")) {
                Object object = message.get("targetId");
                if (object instanceof Integer) {
                    targetId = (Integer) object;
                } else if (object instanceof String) {
                    targetId = Integer.parseInt((String) object);
                } else {
                    // wrong type
                    throw new XRECommandHandlerException("The targetId is wrong type.");
                }
            }
            if (message.has("targetPath")) {
                targetPath = message.getString("targetPath");
            }
            if (targetId == 0 && ReceiverUtil.isEmpty(targetPath)) {
                throw new XRECommandHandlerException("Either targetId or targetPath must be provided.");
            }

            XREObject target = receiver.getApplicationData().getElementsXREIdToElement().get(targetId);
            if (target == null) {
                return;
                //throw new XRECommandHandlerException("Can't find the target object with targetId [" + targetId + "].");
            }
            target.setProperties(message);
        } catch (JSONException e) {
            throw new XRECommandHandlerException("Error occurs when reading from json.", e);
        } catch (NumberFormatException e) {
            throw new XRECommandHandlerException("TargetId must be an integer.", e);
        } catch (XREObjectFormatterException e) {
            throw new XRECommandHandlerException("Can't set properties to the target object.", e);
        }
    }
}
